#include "DataStructures.h"
#include "HCI.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include "millis.h"
#include <util/delay.h>


int btn1;
int btn1Last;
int btn2;
int btn2Last;
int btn1StartTime;
int btn2StartTime;
int PortD_State;

void HCISetup()
{
  DDRD |= (1<<3 |1<<5); //output
  
  ////turn on LEDs for a moment to show they work
  PORTD |= (1<<3 |1<<5);
  _delay_ms(1000);
  PORTD &= ~(1<<3 |1<<5);

  

}
//
void HCILoop()
{
  
  cli();  // so button states can't be changed and in turn overwritten to old values
  PortD_State = PORTD & (1<<3 |1<<5); //remember led state
  DDRD &= ~(1<<3 |1<<5); //input

  btn1 = PIND & (1<<3);
  btn2 = PIND & (1<<5);

  PORTD |= PortD_State; // restore LED state
  sei();

  // ***Button 1 analysis***
  if(btn1 && !btn1Last) //depress
  {
    btn1StartTime = millis();
    btn1Last = btn1;
  }

  if(!btn1 && btn1Last) //release
  {
    int btn1PressDuration = millis()-btn1StartTime;
    if(btn1PressDuration>75)
    {
      if (btn1PressDuration < 2100) //short press
      {
        buttonData.btnPressedEvent = HCIDATA_BUTTONPRESSEDEVENT_BUTTON1_SHORTPRESS;
        buttonData.dataFresh = 1;
      }
      else //long press
      {
        buttonData.btnPressedEvent = HCIDATA_BUTTONPRESSEDEVENT_BUTTON1_LONGPRESS;
        buttonData.dataFresh = 1;
      }
    }      
    
  btn1Last = btn1;
  }
  
  // ***Button 2 analysis***
  if(btn2 && !btn2Last) //depress
  {
    btn2StartTime = millis();
    btn2Last = btn1;
  }

  if(!btn2 && btn2Last) //release
  {
    int btn2PressDuration = millis()-btn2StartTime;
    if(btn2PressDuration>75)
    {
      if (btn2PressDuration < 2100) //short press
      {
        buttonData.btnPressedEvent = HCIDATA_BUTTONPRESSEDEVENT_BUTTON2_SHORTPRESS;
        buttonData.dataFresh = 1;
        //HCIButton2
      }
      else //long press
      {
        buttonData.btnPressedEvent = HCIDATA_BUTTONPRESSEDEVENT_BUTTON2_LONGPRESS;
        buttonData.dataFresh = 1;
        //
      }
    }
    
    btn1Last = btn1;
  }
  
}
